<!-- 装修课程组件：课程卡片 -->
<template>
  <!-- 课程卡片 -->
  <view>
    <!-- 布局1. 单列大图（上图，下内容）-->
    <view v-if="layoutType === LayoutTypeEnum.ONE_COL_BIG_IMG && state.goodsList.length" class="goods-sl-box">
      <view class="goods-box" v-for="item in state.goodsList" :key="item.id"
        :style="[{ marginBottom: data.space * 2 + 'rpx' }]">
        <s-course-column class="" size="sl" :goodsFields="data.fields" :tagStyle="data.badge" :data="item"
          :titleColor="data.fields.name?.color" :subTitleColor="data.fields.introduction.color"
          :topRadius="data.borderRadiusTop" :bottomRadius="data.borderRadiusBottom" @click="goDetail(item)">
          <!-- 购买按钮 -->
          <template v-slot:cart>
            <button class="ss-reset-button cart-btn" :style="[buyStyle]">
              {{ btnBuy.type === 'text' ? btnBuy.text : '' }}
            </button>
          </template>
        </s-course-column>
      </view>

      <uni-load-more v-if="state.pagination.total > 5" :status="state.loadStatus" :content-text="{
	      contentdown: '展开更多',
	    }" @tap="loadMore" />
    </view>
  </view>

  <!-- 布局2. 双列（每一列：上图，下内容）-->
  <view v-if="layoutType === LayoutTypeEnum.TWO_COL && state.goodsList.length"
    class="goods-md-wrap ss-flex ss-flex-wrap ss-col-top">
    <view class="goods-list-box">
      <view class="left-list" :style="[{ paddingRight: data.space + 'rpx', marginBottom: data.space + 'px' }]"
        v-for="item in state.leftGoodsList" :key="item.id">
        <s-course-column class="goods-md-box" size="md" :goodsFields="data.fields" :tagStyle="data.badge" :data="item"
          :titleColor="data.fields.name?.color" :subTitleColor="data.fields.introduction.color"
          :topRadius="data.borderRadiusTop" :bottomRadius="data.borderRadiusBottom"
          :titleWidth="330 - marginLeft - marginRight" @click="goDetail(item)"
          @getHeight="calculateGoodsColumn($event, 'left')">
          <!-- 购买按钮 -->
          <template v-slot:cart>
            <button class="ss-reset-button cart-btn" :style="[buyStyle]">
              {{ btnBuy.type === 'text' ? btnBuy.text : '' }}
            </button>
          </template>
        </s-course-column>
      </view>
    </view>
    <view class="goods-list-box">
      <view class="right-list" :style="[{ paddingLeft: data.space + 'rpx', marginBottom: data.space + 'px' }]"
        v-for="item in state.rightGoodsList" :key="item.id">
        <s-course-column class="goods-md-box" size="md" :goodsFields="data.fields" :tagStyle="data.badge" :data="item"
          :titleColor="data.fields.name?.color" :subTitleColor="data.fields.introduction.color"
          :topRadius="data.borderRadiusTop" :bottomRadius="data.borderRadiusBottom"
          :titleWidth="330 - marginLeft - marginRight" @click="goDetail(item)"
          @getHeight="calculateGoodsColumn($event, 'right')">
          <!-- 购买按钮 -->
          <template v-slot:cart>
            <button class="ss-reset-button cart-btn" :style="[buyStyle]">
              {{ btnBuy.type === 'text' ? btnBuy.text : '' }}
            </button>
          </template>
        </s-course-column>
      </view>
    </view>
  </view>

  <!-- 布局3. 单列小图（左图，右内容） -->
  <view v-if="layoutType === LayoutTypeEnum.ONE_COL_SMALL_IMG && state.goodsList.length" class="goods-lg-box">
    <view class="goods-box" :style="[{ marginBottom: data.space + 'px' }]" v-for="item in state.goodsList"
      :key="item.id">
      <s-course-column class="goods-card" size="lg" :goodsFields="data.fields" :data="item" :tagStyle="data.badge"
        :titleColor="data.fields.name?.color" :subTitleColor="data.fields.introduction.color"
        :topRadius="data.borderRadiusTop" :bottomRadius="data.borderRadiusBottom" @tap="goDetail(item)">
        <!-- 购买按钮 -->
        <template v-slot:cart>
          <button class="ss-reset-button cart-btn" :style="[buyStyle]">
            {{ btnBuy.type === 'text' ? btnBuy.text : '' }}
          </button>
        </template>
      </s-course-column>
    </view>
  </view>
</template>

<script setup>
  /**
   * 课程卡片
   */
  import jweixin from 'weixin-js-sdk';
  import {
    computed,
    onMounted,
    ref,
    reactive
  } from 'vue';
  import {
    onLoad
  } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import SpuApi from '@/sheep/api/product/spu';
  import AreaApi from '@/sheep/api/system/area';
  import OrderApi from '@/sheep/api/trade/order';
  import {
    appendSettlementProduct
  } from '@/sheep/hooks/useGoods';
  import _ from 'lodash-es';
  let pickUpStoreId = ref('')
  // 布局类型
  const LayoutTypeEnum = {
    // 单列大图
    ONE_COL_BIG_IMG: 'oneColBigImg',
    // 双列
    TWO_COL: 'twoCol',
    // 单列小图
    ONE_COL_SMALL_IMG: 'oneColSmallImg',
  };

  const state = reactive({
    goodsList: [],
    leftGoodsList: [],
    rightGoodsList: [],
    pagination: {
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 5,
    },
    loadStatus: '',
  });
  const props = defineProps({
    data: {
      type: Object,
      default: () => ({}),
    },
    styles: {
      type: Object,
      default: () => ({}),
    },
  });


  const {
    layoutType,
    btnBuy,
    spuIds
  } = props.data || {};
  const {
    marginLeft,
    marginRight
  } = props.styles || {};

  // 购买按钮样式
  const buyStyle = computed(() => {
    if (btnBuy.type === 'text') {
      // 文字按钮：线性渐变背景颜色
      return {
        background: `linear-gradient(to right, ${btnBuy.bgBeginColor}, ${btnBuy.bgEndColor})`,
      };
    }
    if (btnBuy.type === 'img') {
      // 图片按钮
      return {
        width: '54rpx',
        height: '54rpx',
        background: `url(${sheep.$url.cdn(btnBuy.imgUrl)}) no-repeat`,
        backgroundSize: '100% 100%',
      };
    }
  });

  //region 课程瀑布流布局
  // 下一个要处理的课程索引
  let count = 0;
  // 左列的高度
  let leftHeight = 0;
  // 右列的高度
  let rightHeight = 0;

  /**
   * 计算课程在左列还是右列
   * @param height 课程的高度
   * @param where 添加到哪一列
   */
  function calculateGoodsColumn(height = 0, where = 'left') {
    // 处理完
    if (!state.goodsList[count]) return;
    // 增加列的高度
    if (where === 'left') leftHeight += height;
    if (where === 'right') rightHeight += height;
    // 添加到矮的一列
    if (leftHeight <= rightHeight) {
      state.leftGoodsList.push(state.goodsList[count]);
    } else {
      state.rightGoodsList.push(state.goodsList[count]);
    }
    // 计数
    count++;
  }

  //endregion

  /**
   * 根据课程编号列表，获取课程列表
   * @param ids 课程编号列表
   * @return {Promise<undefined>} 课程列表
   */
  async function getGoodsListByIds(ids) {
    const {
      data
    } = await SpuApi.getSpuListByIds(ids);
    return data;
  }

  function goDetail(item) {
    if (item.productType == 1) {
      sheep.$router.go('/pages/course/index', {
        id: item.id
      })
    } else if (item.productType === 2) {
      sheep.$router.go('/pages/huodong/index', {
        id: item.id
      })
    } else {
      sheep.$router.go('/pages/goods/index', {
        id: item.id
      })
    }
  }

  // 加载更多
  function loadMore() {
    if (state.loadStatus === 'noMore') {
      return;
    }
    state.pagination.pageNo++;
    loadData();
  }

  // 获取订单列表
  async function loadData() {
    state.loadStatus = 'loading';

    // 加载课程列表
    let param = {
      ids: "",
      productType: 1,
      pickUpStoreId: pickUpStoreId.value,
      categoryId: 84,
      pageNo: state.pagination.pageNo,
      pageSize: state.pagination.pageSize,
      latitude: uni.getStorageSync('user_latitude') || '',
      longitude: uni.getStorageSync('user_longitude') || '',
      tabType: 0
    }
    if (spuIds.length > 0) {
      param.ids = spuIds.join(',');
    }
    let {
      code,
      data
    } = await SpuApi.getSpuPage(param)
    if (code !== 0) {
      return;
    }
    state.goodsList.splice(0, state.goodsList.length)
    state.goodsList = _.concat(state.goodsList, data.list);
    state.pagination.list = _.concat(state.pagination.list, data.list);
    state.pagination.total = data.total;
    state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';
    // 拼接结算信息（营销）
    // await OrderApi.getSettlementProduct(state.goodsList.map((item) => item.id).join(',')).then(
    //   (res) => {
    //     if (res.code !== 0) {
    //       return;
    //     }
    //     appendSettlementProduct(state.goodsList, res.data);
    //   },
    // );
  }
  // // 获取当前经纬度
  // const getLatLong = async () => {
  //   return new Promise((reslove, rej) => {
  //     let latitude = uni.getStorageSync('user_latitude');
  //     let longitude = uni.getStorageSync('user_longitude');
  //     if (latitude && longitude) {
  //       reslove({
  //         latitude,
  //         longitude
  //       })
  //     } else {
  //       uni.getLocation({
  //         type: 'wgs84',
  //         success: (res) => {
  //           uni.setStorageSync('user_latitude', res.latitude);
  //           uni.setStorageSync('user_longitude', res.longitude);
  //           reslove({
  //             latitude: res.latitude,
  //             longitude: res.longitude
  //           })
  //         },
  //         fail: function(e) {
  //           console.log(e)
  //         }
  //       })
  //     }
  //   })
  // }

  // 初始化
  // #ifndef MP-WEIXIN
  onLoad(async () => {
          // #endif
          // #ifdef MP-WEIXIN
          onMounted(async () => {
            // #endif
            // console.log('s-course-card')
            uni.$on('updateVillage', async (data) => {
              if (data) {
                pickUpStoreId.value = data.villageId
                await loadData();
                return
              }
            })
            const isLogin = computed(() => sheep.$store('user').isLogin);
            // let result = await AreaApi.getVillage()
            // if (result.code == 0 && result?.data) {
            //   pickUpStoreId.value = result.data.id
            //   await loadData();
            // }
            // if (isLogin.value) {
            //   let res = await getLatLong()
            //   根据经纬度获取小区列表
            //   let result = await AreaApi.getVillageList(res)
            //   if (result.code == 0 && result?.data?.length) {
            //     pickUpStoreId.value = result.data[0].id
            //     await loadData();
            //   }
            // }
            await loadData();

            // 只有双列布局时需要
            if (layoutType === LayoutTypeEnum.TWO_COL) {
              // 分列
              calculateGoodsColumn();
            }
          });
</script>

<style lang="scss" scoped>
  .goods-md-wrap {
    width: 100%;
  }

  .goods-list-box {
    width: 50%;
    box-sizing: border-box;

    .left-list {
      &:nth-last-child(1) {
        margin-bottom: 0 !important;
      }
    }

    .right-list {
      &:nth-last-child(1) {
        margin-bottom: 0 !important;
      }
    }
  }

  .goods-box {
    &:nth-last-of-type(1) {
      margin-bottom: 0 !important;
    }
  }

  .goods-md-box,
  .goods-sl-box,
  .goods-lg-box {
    position: relative;

    .cart-btn {
      position: absolute;
      bottom: 18rpx;
      right: 20rpx;
      z-index: 11;
      height: 50rpx;
      line-height: 50rpx;
      padding: 0 20rpx;
      border-radius: 25rpx;
      font-size: 24rpx;
      color: #fff;
    }
  }
</style>